// pages/scoreMall/perfectOrder/perfectOrder.js
const orderService = require('../../../api/orderService.js')
const util = require('../../../utils/utils.js')

//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentStoreInfo: {
      storeId: '',
      storeName: '未获取到门店信息'
    },
    goodsList: [],
    scoreInfo: {},
    integral: 0,
    allPrice: 0.00,
    type: 'selftake',
    date: '2016-09-01',
    time: '12:01',
    multiArray: [
      ['2018-06-01', '2018-06-02', '2018-06-03'],
      ['6:00-9:00', '9:00-12:00', '12:00-15:00', '15:00-18:00', '18:00-21:00']
    ],
    multiIndex: [0, 0],
    canBuy: true,
    remarks: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.storeInfo) {
      this.setData({
        currentStoreInfo: {
          storeId: app.globalData.storeInfo.id,
          storeName: app.globalData.storeInfo.name
        }
      })
    }
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      this.setData({
        userInfo: app.globalData.userInfo.member
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const self = this
    try {
      // 获取购物车数据
      var value = wx.getStorageSync('wj_shopcart')
      if (value) {
        console.log(value)
        self.setData({
          goodsList: value.goodsList,
          allPrice: parseFloat(value.allPrice),
          storeId: value.storeId,
          orderType: value.orderType,
          scoreInfo: {
            scoreAmount: value.allPrice,
          },
          integral: value.score,
          scoreUseAmount: value.score
        })
        if (value.scource) {
          self.setData({
            scource: value.scource,
          })
        }
        // 检查商品售卖时间
        self.initializationTime() //初始化预约时间
      }
      var remarks = wx.getStorageSync('_orderRemark_')
      if (remarks) {
        this.setData({
          remarks: remarks
        })
      }
    } catch (e) {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.clearCacheData()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
  },
  bindMultiPickerColumnChange: function (e) {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    var now = new Date();
    let tempStart = this.data.storeTime[0] + ':00'
    let tempEnd = this.data.storeTime[1] + ':00'
    let date = util.formatTime(now).split(" ")[0]
    var startTimeDetails = new Date(date + " " + tempStart).getTime()
    var endTimeDetails = new Date(date + " " + tempEnd).getTime()
    var nowTime = new Date(util.formatTime(now)).getTime()
    switch (data.multiIndex[0]) {
      case 0:
        if (nowTime < endTimeDetails && nowTime > startTimeDetails) {
          data.multiArray[1] = this.data.chooseTime[1]
        }
        break;
      case 1:
        data.multiArray[1] = this.data.chooseTime[0];
        break;
      case 2:
        data.multiArray[1] = this.data.chooseTime[0];
        break;
    }
    if (data.multiArray[1][0] === '请选择其他时间' || data.multiArray[1][0] === '不能下单') {
      this.setData({
        canBuy: false
      });
    } else {
      this.setData({
        canBuy: true
      });
    }
    this.setData(data);
  },
  //初始化预约时间
  initializationTime: function () {
    const self = this
    var now = new Date();
    var hour = now.getHours(); //小时数
    let days = 3
    var tempTime = [
      [],
      []
    ]
    for (let i = 0; i < days; i++) {
      let date = self.addDay(now, i)
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      let newDate = [year, month, day].map(util.timeFormat).join('-')
      tempTime[0].push(newDate)
    }
    tempTime[1] = this.handleChooseTime()
    this.setData({
      multiArray: tempTime,
    })
  },

  handleChooseTime: function () {
    const self = this
    var now = new Date();
    var hour = now.getHours(); //小时数
    var minute = now.getMinutes(); //分钟数
    var time = [hour, minute].map(util.timeFormat).join(':')
    let storeTime = ''
    let tempTime = []
    var businessHours = []
    // 处理经营时间
    try {
      var allStores = wx.getStorageSync('_allStores_')
      console.log(this.data.currentStoreInfo.storeId)
      var reg = new RegExp(this.data.currentStoreInfo.storeId);
      if (allStores) {
        allStores.forEach(item => {
          if (reg.test(item.id)) {
            storeTime = item.storeHours.split("-")
          }
        })
      }
    } catch (e) { }
    console.log(storeTime)
    let tempStart = storeTime[0] + ':00'
    let tempEnd = storeTime[1] + ':00'
    let date = util.formatTime(now).split(" ")[0]
    var startTimeDetails = new Date(date + " " + tempStart).getTime()
    var endTimeDetails = new Date(date + " " + tempEnd).getTime()
    var nowTime = new Date(util.formatTime(now)).getTime()
    businessHours = this.splitTime(date, date, 10800000, tempStart, tempEnd);
    let hourArray = [] //营业时间小时数组
    businessHours.forEach(ele => {
      hourArray.push(ele.slice(0, 2))
    });
    let hourArrayLength = hourArray.length
    console.log(businessHours)
    let chooseTime = [
      [],
      []
    ]
    for (let j = 0; j < businessHours.length - 1; j++) {
      const eleStart = businessHours[j];
      const eleEnd = businessHours[j + 1];
      let tempData = eleStart + '-' + eleEnd
      chooseTime[0].push(tempData)
    }
    for (let i = 0; i < hourArray.length; i++) {
      if (hour >= hourArray[i] && hour < hourArray[i + 1]) {
        chooseTime[1].push(time + '-' + businessHours[i + 1])
        for (let k = i + 1; k < businessHours.length - 1; k++) {
          const eleStart = businessHours[k];
          const eleEnd = businessHours[k + 1];
          let tempData = eleStart + '-' + eleEnd
          chooseTime[1].push(tempData)
        }
      }
    }
    self.setData({
      chooseTime: chooseTime,
      storeTime: storeTime
    })
    console.log(hourArray[hourArrayLength - 1])
    // 小时
    if (nowTime < startTimeDetails || nowTime < endTimeDetails) {
      tempTime = chooseTime[1];
    } else {
      tempTime = chooseTime[0]
    }
    if (self.data.orderType === 'advanceSell') {
      // 预售
      tempTime = chooseTime[0]
    }
    console.log(tempTime)
    return tempTime
  },
  /**
   * 通过营业时间进行计算返回3小时间隔的时间数组
   * @param startDate 起始时间 xxxx/xx/xx
   * @param endDate 结束时间 xxxx/xx/xx
   * @param amount 时间间隔 毫秒
   */
  splitTime: function (startDate, endDate, amount, timeStart, timeEnd) {
    var startTime = new Date(startDate + " " + timeStart)
    var endTime = new Date(endDate + " " + timeEnd)
    var gap = amount;
    let count = Math.ceil((endTime - startTime) / gap)
    let realCount = (endTime - startTime) / gap
    console.log(count)
    var temp = [];
    let tempTime = []
    if (count - realCount >= 0) {
      temp.push(util.formatTime(startTime))
      for (var i = 1; i < count; i++) {
        startTime.setMilliseconds(startTime.getMilliseconds() + gap);
        temp[i] = util.formatTime(new Date(startTime.getTime()));
      }
      temp.push(util.formatTime(endTime))
    } else {
      temp.push(util.formatTime(startTime))
      for (var i = 1; i < count; i++) {
        startTime.setMilliseconds(startTime.getMilliseconds() + gap);
        temp[i] = util.formatTime(new Date(startTime.getTime()));
      }
    }
    temp.forEach(item => {
      let tempData = item.split(" ")[1].slice(0, 5);
      tempTime.push(tempData)
    });
    tempTime = Array.from(new Set(tempTime))
    return tempTime;
  },
  addDay: function (curDate, days) {
    return new Date((curDate / 1000 + (86400 * days)) * 1000)
  },
  getPostData: function () {
    const that = this
    let products = [];
    this.data.goodsList.forEach(item => {
      products.push({
        productId: item.productId,
        productNum: item.productNum
      })
    })
    var postData = '';
    var tempSelfTime = null;
    let shipmentType = 'self';
    let tempShipAmount = 0;
    const distributionInfo = that.data.distributionInfo
    const freeshipDiscount = that.data.freeshipCoupon
    if (this.data.type === 'dispatch') {
      shipmentType = 'EXPRESS';
      if (distributionInfo.distributioCompany === "DEFAULT") {
        tempShipAmount = distributionInfo.baseFare
      } else {
        tempShipAmount = distributionInfo.distributionFee
      }
      let tempFreeship = tempShipAmount - freeshipDiscount
      that.setData({
        shipmentDiscount: tempFreeship.toFixed(2),
      })
    } else {
      shipmentType = 'SELF';
      tempSelfTime = this.data.multiArray[0][this.data.multiIndex[0]] + ' ' + this.data.multiArray[1][this.data.multiIndex[1]];
    }
    let paymentPrice = parseFloat(this.data.allPrice - this.data.couponPrice + tempShipAmount)
    if (paymentPrice >= 0) {
      paymentPrice = paymentPrice.toFixed(2)
    } else {
      paymentPrice = 0
    }

    console.log(this.data.addressInfo)
    postData = {
      allPrice: paymentPrice, // 应该支付的金额
      products: products, // 商品列表
      receiverMobile: this.data.userInfo.mobile ? this.data.userInfo.mobile : '', // 收货人手机号
      remark: this.data.remarks ? this.data.remarks : '', // 备注
      scource: 'BUYNOW', // 来自购物车SHOPPINGCART 立即购买BUYNOW
      shipmentAmount: tempShipAmount, // 快递费
      shipmentType: shipmentType, // 配送方式
      selfTimeScope: tempSelfTime, // 预约自提时间
      storeId: this.data.currentStoreInfo.storeId, // 门店id
      score: that.data.integral,
      orderSource: 'MINI_APP'
    }
    console.log(shipmentType)
    if (shipmentType === 'EXPRESS') {
      if (this.data.addressInfo) {
        postData = {
          ...postData,
          deliveryAddressId: this.data.addressInfo.id, // 收货地址id
          distributionDistance: this.data.distance, // 配送距离
        }
      } else {

      }
    }
    return postData;
  },
  /**
   * 创建订单
   */
  createOrder: function (val) {
    const self = this
    let postData = this.getPostData();
    var deliveryStatus = true
    console.log(postData)
    try {
      // 清除部分缓存数据，以免对其他订单造成影响
      wx.removeStorageSync('_orderRemark_')
      wx.removeStorageSync('wj_shopcart')
    } catch (e) { }
    if (postData.shipmentType === 'EXPRESS') {
      if (!postData.deliveryAddressId) {
        deliveryStatus = false
      } else {
        deliveryStatus = true
      }
    }
    let orderType = this.data.orderType
    if (deliveryStatus) {
      if (self.data.canBuy) {
        this.setData({
          canBuy: false
        })
        try {
          wx.setStorageSync('wj_wxa_formId', val.detail.formId)
        } catch (e) { }
        orderService.createScoreOrder(postData).then(res => {
          console.log(res)
          self.clearCacheData()
          self.getPay(res)
        }).catch(err => {
          console.log(err)
          if (err.code === 14009) {
            // 门店已经暂停线上下单
            self.getAllStore()
            wx.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000
            })
          } else if (err.code === 16001) {
            wx.showToast({
              title: '商品暂未上架，请到别的门店看看吧！',
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000
            })
          }
          self.setData({
            canBuy: true
          })
        })
      }
    } else {
      wx.showToast({
        title: '收货地址不能为空~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  /**
   * 清除缓存
   */
  clearCacheData: function () {
    try {
      wx.removeStorageSync('wj_shopcart')
      wx.removeStorageSync('_orderRemark_')
    } catch (e) { }
  },
  /**
   * 订单支付
   */
  getPay: function (order) {
    const self = this
    if (order.cashTotal === 0) {
      self.toPaymentSuccess(order.id)
    } else {
      // 调用接口获取支付签名，调用微信支付
    }
  },
  /**
   * 订单兑换成功
   */
  toPaymentSuccess: function (orderId) {
    wx.redirectTo({
      url: '../scorePaySuccess/scorePaySuccess?orderId=' + orderId
    })
  },
  /**
   * 添加备注
   */
  addRemarks: function () {
    wx.navigateTo({
      url: '../addRemarks/addRemarks',
    })
  }
})